import 'dart:async';

import 'package:flutter/material.dart';
import 'package:library_base/base/base_app_state_page.dart';
import 'package:library_base/constant/constant.dart';
import 'package:library_base/event/event.dart';
import 'package:library_base/ext/theme_data_ext.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:get/get.dart';
import 'package:library_base/res/gaps.dart';
import 'package:library_base/res/styles.dart';
import 'package:library_base/utils/theme_util.dart';
import 'package:library_base/widget/dialog/dialog_util.dart';
import 'package:library_base/widget/image/local_image.dart';
import 'package:extended_tabs/extended_tabs.dart';
import 'package:library_base/widget/nestedscroll/nested_scroll_view_inner_scroll_position_key_widget.dart'
    as extended;
import 'package:library_base/widget/tab/round_indicator.dart';
import 'package:module_dispatcher/page/dispatcher_main_controller.dart';
import 'package:module_dispatcher/page/progress/progress_page.dart';
import 'package:module_dispatcher/page/scheduled/scheduled_page.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:library_base/entities/event/dispatcher_goods_count.dart';

class DispatcherMainPage extends StatefulWidget {
  const DispatcherMainPage({Key? key}) : super(key: key);

  @override
  State<DispatcherMainPage> createState() => _DispatcherMainPageState();
}

class _DispatcherMainPageState extends BaseState<DispatcherMainPage, DispatcherMainController>
    with SingleTickerProviderStateMixin {

  late StreamSubscription<DispatcherGoodsCount> streamSubscription;

  final pageController = PageController();

  late TabController _tabController;

  final List<String> _tabTitles = [
    MultiLanguage.toBeScheduled.tr,
    MultiLanguage.inProgress.tr,
  ];

  @override
  void onCreate() {
    setNavigationBarVisible(false);
    setStatusBarVisible(true);
    setStatusBarColor(ThemeUtil.getTheme().colorScheme.secondary);
    _tabController = TabController(length: 2, vsync: this);
    streamSubscription = Event.eventBus.on<DispatcherGoodsCount>().listen((event) {
      if (event.page == 0) {
        baseGetxController!.count.value = event.count;
      } else {
        baseGetxController!.count1.value = event.count;
      }
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  void controllerOnCreate() {
    super.controllerOnCreate();
    baseGetxController!.tabController = _tabController;
  }

  @override
  Widget? getMainWidget(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeUtil.getTheme().colorScheme.secondary,
      body: Stack(
        children: [
          Column(
            children: <Widget>[
              Row(
                children: [
                  Container(
                    height: 100.r,
                    alignment: Alignment.centerLeft,
                    child: TabBar(
                      isScrollable: true,
                      controller: _tabController,
                      labelColor: ThemeUtil.getTheme().primaryColor,
                      labelStyle: normalBoldTextColor32,
                      unselectedLabelColor: ThemeUtil.getTheme().normalTextColor(),
                      unselectedLabelStyle: normalTextColor28,
                      indicatorSize: TabBarIndicatorSize.label,
                      indicator: RoundTabIndicator(
                          borderSide:
                              BorderSide(color: ThemeUtil.getTheme().primaryColor, width: 3),
                          isRound: true,
                          insets: EdgeInsets.only(left: 20.r, right: 20.r)),
                      onTap: (index) {
                        baseGetxController!.update();
                      },
                      tabs: <Tab>[
                        Tab(text: _tabTitles[0]),
                        Tab(text: _tabTitles[1]),
                      ],
                    ),
                  ),
                  Expanded(
                    child: GestureDetector(
                      onTap: showTimePicker,
                      child: GetBuilder<DispatcherMainController>(
                        assignId: true,
                        builder: (logic) {
                          return Row(
                              mainAxisSize: MainAxisSize.min,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                Visibility(
                                  visible: false,
                                  child: Text(
                                      MultiLanguage.productsInTotal.trArgs([
                                        "${_tabController.index == 0 ? baseGetxController!.count : baseGetxController!.count1}"
                                      ]),
                                      style: sixthTextColor26),
                                ),
                                gapW15,
                                LocalImage('common_filter',
                                    package: Constant.packLib(), width: 38.w, height: 38.w),
                                gapW24,
                              ]);
                        },
                      ),
                    ),
                  ),
                ],
              ),
              Expanded(
                  child: ExtendedTabBarView(
                controller: _tabController,
                pageController: pageController,
                children: <Widget>[
                  extended.NestedScrollViewInnerScrollPositionKeyWidget(
                      Key(_tabTitles[0]), const ScheduledPage()),
                  extended.NestedScrollViewInnerScrollPositionKeyWidget(
                      Key(_tabTitles[1]), const ProgressPage()),
                ],
              ))
            ],
          ),
          buildFloating(),
        ],
      ),
    );
  }

  Widget buildFloating() {
    return Positioned(
      right: 24.w,
      bottom: 224.h,
      child: GestureDetector(
          onTap: () {
            Get.back();
          },
          child: Opacity(
            opacity: 0.5,
            child: Container(
                alignment: Alignment.centerRight,
                child: LocalImage('common_back_main',
                    package: Constant.packLib(), width: 130.r, height: 130.r, fit: BoxFit.cover)),
          )),
    );
  }

  showTimePicker() {
    var map = <String, dynamic>{};
    if (_tabController.index == 0) {
      if (baseGetxController!.stationTimeBegin0.isNotEmpty) {
        map['currentTime'] = DateTime.parse(baseGetxController!.stationTimeBegin0);
      } else {
        map['currentTime'] = null;
      }
    } else {
      if (baseGetxController!.stationTimeBegin1.isNotEmpty) {
        map['currentTime'] = DateTime.parse(baseGetxController!.stationTimeBegin1);
      } else {
        map['currentTime'] = null;
      }
    }
    map['filter'] = baseGetxController!.filter;
    map['reset'] = baseGetxController!.reset;
    DialogUtil.showTimePickDialog(arguments: map);
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    super.dispose();
    pageController.dispose();
    streamSubscription.cancel();
  }

  @override
  DispatcherMainController registerController() => Get.find<DispatcherMainController>();

}
